package mz.matafe.bolao

/**
 * Domain Class for a Team.
 *
 * <p>Represents a team. Eg.: (Brasil, USA)
 *
 * @since 0.0.1
 * @author <a href="mailto:matafe@gmail.com">Maurício T. Ferraz</a>
 */
class Team implements Comparable{

    //services
    def authenticateService

    //properties
    String name
    byte[] flagImage
    Date dateCreated
    Date lastUpdated
    User createdBy
    User updatedBy
    boolean active = true
    TeamDetails teamDetails
    Group group

    static embedded = ['teamDetails']

    static belongsTo = [Group]

    static constraints = {
        name(unique:'group', blank:false, size:1..30)
        flagImage(nullable:true)
        teamDetails()
        group(nullable:true)
        dateCreated()
        lastUpdated()
        createdBy(nullable:true)
        updatedBy(nullable:true)
        active()
    }

    static mapping = {
        table 'WC_TEAM'
        flagImage column: 'flag_image', sqlType: 'varbinary', length: 10000
        sort name:'asc'
        createdBy column: 'CREATED_BY'
        updatedBy column: 'UPDATED_BY'
    }

    def beforeInsert = {
        log.info "Before insert a Team"
        def loggedUser = authenticateService.userDomain()
        this.createdBy = this.createdBy ?: loggedUser
        this.updatedBy = updatedBy ?: loggedUser
    }

    def beforeUpdate = {
        log.info "Updating Team ${id} "
        this.updatedBy = authenticateService.userDomain()
    }

    def afterInsert = {
        log.info "Team ${id} inserted by ${createdBy}"
    }

    def afterUpdate = {
        log.info "Team ${id} updated by ${updatedBy}"
    }

    String toString(){
        "${this.class.name}:id[$id];name[$name]"
    }

    int compareTo(Object o){
        this.id <=> ((Team)o).id
    }
}

/**
 * Embedded Domain Class for a Team Details.
 *
 * <p>Represents a team's detail.
 *
 * @since 0.0.1
 * @author <a href="mailto:matafe@gmail.com">Maurício T. Ferraz</a>
 */
class TeamDetails{
    Integer played = 0
    Integer won = 0
    Integer draw = 0
    Integer lost = 0
    Integer goalsFor = 0
    Integer goalsAgainst = 0
    Integer points = 0

    static constraints = {
        played()
        won()
        draw()
        lost()
        goalsFor()
        goalsAgainst()
        points()
    }

    String toString(){
        'MP:'+played+',W:'+won+',D:'+draw+',L:'+lost+
        ',GF:'+goalsFor+',GA:'+goalsAgainst+',PTS:'+points
    }

    static mapping = {
        played column: 'played'
        won column: 'won'
        draw column: 'draw'
        lost column: 'lost'
        goalsFor column: 'goalsFor'
        goalsAgainst column: 'goalsAgainst'
        points column: 'points'
    }

}